<?php
namespace app\controller;

use app\BaseController;
use app\validate\CheckTask;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use think\exception\ValidateException;


// 积分任务
class IntegralTask extends BaseController
{
    public function index()
    {
        return View::fetch();
    }


    //+积分任务数据加载
    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $where = [];
        $get = $request->get();

        if (isset($get['title'])) {
            if (!empty($get['title'])) {
                $where[] = ['title', 'like', '%'.$get['title'].'%'];
            }
        }


        if (isset($get['type'])) {
            if(!empty($get['type']) && $get['type'] != -1){
                $where[] = ['type', '=', $get['type']];
            }
        }


        $total = Db::name('integral_task')
            ->where($where)
            ->count();

        $rows = Db::name('integral_task')
            ->whereNotIn('id',[20])
            ->where($where)
            ->order('sort', 'asc')
            ->order('id', 'desc')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            if (in_array($v['id'],[19,20,13,14,15,21])) {
                $v['hid_status'] = 1;
            }else{
                $v['hid_status'] = 2;
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function sort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['sort'] < 0 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }

        try {
            $res = Db::name('integral_task')->where('id', '=', $post['id'])->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }

            $rows = Db::name('integral_task')->where('id', '<>', $post['id'])->where('sort', '>=', $post['sort'])->order('sort', 'asc')->select();
            Db::startTrans();
            if (!Db::name('integral_task')->where('id', '=', $post['id'])->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('integral_task')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //+任务开启or关闭
    public function toggle(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        if (!$id = $request->param('id')) {
            return $this->outputAjax();
        }

        try {
            $inf = Db::name('integral_task')->field('status')->find($id);

            if (empty($inf)) {
                return $this->outputAjax();
            }

            if (!in_array($inf['status'], array(1, 2))) {
                return $this->outputAjax();
            }

            $status = $inf['status'] == 1 ? 2 : 1;

            $update = array(
                'id'=> $id,
                'status'=> $status,
            );
            if(Db::name('integral_task')->update($update)) {
                return $this->outputAjax('操作成功', 0);
            }
            return $this->outputAjax('操作失败');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    /*
     * 修改
     */
    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->param('id');

        $inf = Db::name('integral_task')->find($id);
        if (in_array($inf['id'],[13,14,15,19,21])) {
            $inf['hide'] = 1;
        } else {
            $inf['hide'] = 2;
        }
        View::assign('inf',$inf);
        return View::fetch();
    }


    /**
     * 保存
     * @date: 2019年9月29日
     * @author: Administrator
     * @return:
     */
    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckTask::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        if ($post['integral'] < 0 || $post['num'] < 0 || $post['upper_limit'] < 0) {
            return $this->outputAjax('输入框不能填写负数！');
        }

        try {
            $update = array(
                'id'            => $post['id'],
                'title'         => $post['title'],
                'e_title'       => $post['e_title'],
                'intro'         => $post['intro'],
                'e_intro'       => $post['e_intro'],
                'icon'          => $post['icon'],
                'type'          => $post['type'],
                'range'         => $post['range'],
                'integral'      => $post['integral'],
                'num'           => $post['num'],
                'upper_limit'   => $post['upper_limit'],
                'url'           => $post['url'],
                'update_time'   => time(),
            );
            if (!Db::name('integral_task')->update($update)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function showIcon()
    {
        $arr = array(
            array(
                'name' => 'Moments分享',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/1.png'
            ),
            array(
                'name' => 'SPARK',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/SPARK.png'
            ),
            array(
                'name' => '查看排行榜',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/2.png'
            ),
            array(
                'name' => '分享',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/3.png'
            ),
            array(
                'name' => '评论_点赞_关注',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/4.png'
            ),
            array(
                'name' => '签到',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/5.png'
            ),
            array(
                'name' => '视频课',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/6.png'
            ),
            array(
                'name' => '喜马拉雅',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/7.png'
            ),
            array(
                'name' => '学习任务',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/8.png'
            ),
            array(
                'name' => '浏览历史',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/9.png'
            ),
            array(
                'name' => '发帖',
                'value' => 'https://learningspark-resource.lorealchina.com/static/icon/10.png'
            ),
        );
        View::assign('data', $arr);
        return View::fetch();
    }

}